package com.amikomgamedev.labirinhantu;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class Memory_DB	extends	SQLiteOpenHelper
{
    private final static String	DB_NAME		= "hantwo";
    private final static int	DB_VERSION	= 1;
    
    private final String	TABLE_NAME	= "tabeltulang";
    
    private final String	BD_CREATE	= 
	    	"CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
		"(stage INTEGER, " +
		"map INTEGER, " +
		"tulang INTEGER)";
    
    
    private SQLiteDatabase	m_DB;
    private Context		m_Context;

    public Memory_DB(
	    Context context,
	    String name,
	    CursorFactory factory,
	    int version)
    {
	super(context, DB_NAME, null, DB_VERSION);
	
	createTable();
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
//	m_DB.execSQL(BD_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
	// TODO Auto-generated method stub
    }
    
    public void createTable()
    {
	m_DB = this.getWritableDatabase();
	m_DB.execSQL(BD_CREATE);

//	m_DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
	m_DB.close();
    }

    public int getTulang(int p_Stage, int p_Map)
    {
	m_DB	= this.getReadableDatabase();
	
	Cursor cursor	= m_DB.rawQuery("SELECT tulang FROM "+TABLE_NAME+" " +
		"WHERE stage = " + p_Stage + " AND map = " + p_Map, null);
	
	while(cursor.moveToNext())
	{
	    	m_DB.close();	
		return cursor.getInt(0);
	}
	m_DB.close();	
	return 0;
    }
    
    private boolean isNull(int p_Stage, int p_Map)
    {
	m_DB	= this.getReadableDatabase();
	
	Cursor cursor	= m_DB.rawQuery("SELECT tulang FROM "+TABLE_NAME+" " +
		"WHERE stage = " + p_Stage + " AND map = " + p_Map, null);
	
	while(cursor.moveToNext())
	{
	    	m_DB.close();	
		return false;
	}
	m_DB.close();	
	return true;
    }
    
    public void setTulang(int p_Stage, int p_Map, int p_Tulang)
    {
	if (isNull(p_Stage, p_Map))
	{
        	final String	DB_INSERT	=
        		    "INSERT INTO " +TABLE_NAME+ 
        		    " VALUES ('" +p_Stage+ "', '" +p_Map+ "', '" + p_Tulang+ "')";
	    
	    	m_DB	= this.getReadableDatabase();
		m_DB.compileStatement(DB_INSERT).executeInsert();
		m_DB.close();
	}
	else
	{
	    	final String	DB_UPDATE	=
		    "UPDATE " +TABLE_NAME+ 
		    " SET tulang = '" + p_Tulang + "' " +
		    "WHERE stage = '" + p_Stage+ "' AND map = '" + p_Map + "'";
	    
	    	m_DB	= this.getReadableDatabase();
		m_DB.compileStatement(DB_UPDATE).executeInsert();
		m_DB.close();
	}
    }
}
